import { useCallback } from "react";

/**
 * 节流Hook
 *
 * @param {Number} delay 延时
 * @returns Function
 */
const useThrottle = (callback, delay = 1000) => {
  let timer = null;
  const onCallback = useCallback((...arg) => callback && callback(...arg), [callback]);

  return function () {
    let context = this;
    let args = arguments;

    if (!timer) {
      timer = setTimeout(() => {
        clearTimeout(timer);
        timer = null;
        onCallback && onCallback.apply(context, args);
      }, delay);
    }
  };
};

export default useThrottle;
